package boerse.main.Asset;

import boerse.main.Exceptions.NegativeShareCountException;
import boerse.main.Exceptions.NegativeValueException;
import boerse.main.Exceptions.NotEnoughMoneyException;

public class ShareDeposit extends Assets{
	
	ShareItem[] shareDeposit; 
	
	public ShareDeposit(String name) {
		super(name);
		this.shareDeposit = new ShareItem[0];
	}
	
	public void buy(Share share, long quantity, CashAccount cashAccount) throws NotEnoughMoneyException, NegativeValueException
	{
		for(int i = 0; i < shareDeposit.length; ++i) {
			if (shareDeposit[i].getName().equals(share.getName())) {
				shareDeposit[i].addShare(quantity);
                cashAccount.removeMoney(quantity*share.getPrice());
				return;
			}
		}
        cashAccount.removeMoney(quantity*share.getPrice());
        resize(1);
		this.shareDeposit[shareDeposit.length-1] = new ShareItem(quantity, share);
	}
	
	public void sell(Share share, long quantity, CashAccount cashAccount) throws NegativeValueException, NegativeShareCountException
	{	
		for(int i = 0; i < shareDeposit.length; ++i) {
			if (shareDeposit[i].getName().equals(share.getName())) {
				shareDeposit[i].removeShare(quantity);
                cashAccount.addMoney(quantity*share.getPrice());
				if (shareDeposit[i].getQuantity() == 0) {
                    shareDeposit[i] = shareDeposit[shareDeposit.length-1];
					resize(-1);
				}
                return;
			}
		}
		
		throw new NegativeShareCountException();
	}
	
		
	public long determinePrice() {
		long price = 0;
		for(int i = 0; i < shareDeposit.length; ++i) 
			price += shareDeposit[i].determinePrice();
		return price;
	}
	
	
	public String toString() {
		String s = this.name + ":\n\nName:\t\tPrice:\t\tQuantity:";
		
		for (int i = 0; i < shareDeposit.length; i++)
			s = s + "\n" + shareDeposit[i];
		
		return s;
	}
	
	public void resize(int wtd) 
	{
        ShareItem[] shareDepositCopy = new ShareItem[shareDeposit.length+wtd];
        if (wtd == 1) {
            for (int i = 0; i < shareDeposit.length;++i )
                    shareDepositCopy[i] = shareDeposit[i];
            }
        else
        {
            for (int i = 0; i < shareDeposit.length+wtd;++i )
                shareDepositCopy[i] = shareDeposit[i];
        }
        shareDeposit = shareDepositCopy;

    }
}

